package cn.net.greenet.policybank.servlet;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Policyrepositoryinstance;
import cn.net.greenet.user.operation.UserPolicyBankAction;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * 删除制定的策略仓库
 *
 * @author liangdelin
 */
@WebServlet(name = "cn.net.greenet.policybank.servlet.Delete", urlPatterns = {"/policy/deletePRI"})
public class Delete extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id"); //创建策略仓库类型名称
        String type = request.getParameter("type"); //创建策略仓库类型名称
        String instance = request.getParameter("instance");  //创建策略仓库实例名称
        HttpSession hsession = request.getSession(false);
        String username = null;
        try {
            username = hsession.getAttribute("name").toString();
        } catch (Exception e) {
            response.sendRedirect("/WebManage/404.html");
        }
        System.out.println("type" + type);
        System.out.println("instance" + instance);
        //删除一个指定类型的策略仓库实例
//        PolicySupport.getInstance().getApi().deleteRepository(type.trim(), instance.trim());
        PrintWriter out = response.getWriter();
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.clear();
        Transaction tx = null;
        try {

            //delete DPIEndPointBean_has_PolicyRepositoryInstance
            BaseDao baseDao = new BaseDao();
            baseDao.executeUpdate("delete FROM DPIEndPointBean_has_PolicyRepositoryInstance where PolicyRepositoryInstance_id = ?", new Object[]{id});
            System.out.println("删除策略仓库与DPI的关系");

            //delete versionmanaged
            baseDao.executeUpdate("delete FROM versionmanaged where PolicyRepositoryInstance_id = ?", new Object[]{id});
            System.out.println("删除策略与 versionmanaged 的关系");

            //delete versionreported
            baseDao.executeUpdate("delete FROM versionreported where PolicyRepositoryInstance_id = ?", new Object[]{id});
            System.out.println("删除策略与 versionreported 的关系");

            //delete policysynchronizationitem
            ResultSet rs3 = baseDao.executeSQL("select PolicySynchronization_id from policysynchronizationitem where PolicyRepositoryInstance_id = ?", new Object[]{id});
            long PolicySynchronization_id = 0;
            while (rs3.next()) {
                PolicySynchronization_id = rs3.getLong("PolicySynchronization_id");
            }

            baseDao.executeUpdate("delete FROM policysynchronization where id = ?", new Object[]{PolicySynchronization_id});
            System.out.println("删除策略与 policysynchronization 的关系");

            baseDao.executeUpdate("delete FROM policysynchronizationitem where PolicySynchronization_id = ?", new Object[]{id});
            System.out.println("删除策略与 policysynchronizationitem 的关系");

            Policyrepositoryinstance bean = (Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, Integer.parseInt(id));
            tx = session.beginTransaction();
            session.delete(bean);
            tx.commit();

            UserPolicyBankAction.deletePolicyBank(username, instance, type);  //写入用户删除策略仓库日志
            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
            out.println("{\"result\":\"false\"}");
        } finally {
            out.close();
            session.close();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
